package com.sun.mybatisplus.filter;

import org.owasp.validator.html.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class XSSRequestWrapper extends HttpServletRequestWrapper {

    //获取antimy框架所需要的决策文件路径
    private static String path = XSSRequestWrapper.class.getClassLoader().getResource("antisamy-test.xml").getFile();

    public XSSRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    public static Policy policy = null;

    static {
        try {
            //过滤策略对象
            policy = Policy.getInstance(path);
        } catch (PolicyException e) {
            e.printStackTrace();
        }
    }


    //通过antisamy过滤字段
    public String cleanXss(String text) {
        AntiSamy antiSamy = new AntiSamy();
        try {
            CleanResults cleanResults = antiSamy.scan(text, policy);
            //过滤之后重新付给text
            text = cleanResults.getCleanHTML();
        } catch (ScanException e) {
            e.printStackTrace();
        } catch (PolicyException e) {
            e.printStackTrace();
        }
        return text;
    }


    /**
     * 当过滤器进行放行的时候这个方法就会被调用
     *
     * @param name
     * @return
     */
    @Override
    public String[] getParameterValues(String name) {
        String[] parameterValues = super.getParameterValues(name);
        if (parameterValues == null) {
            return null;
        }
        String[] newArray = new String[parameterValues.length];
        for (int i = parameterValues.length - 1; i >= 0; i--) {
            String parameterValue = parameterValues[i]; // <script> </script>
            //清理数据后重新赋值
            parameterValue = cleanXss(parameterValue);
            newArray[i] = parameterValue;
        }
        return newArray;
    }
}
